package org.jeeasy.common.core.tools;

import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;

public interface GenericUtil<T> {


    default Class<T> getGenericInterfaces(Class<?> clazz, int index) {
        Type[] genericInterfaces = clazz.getGenericInterfaces();
        ParameterizedType type = (ParameterizedType) genericInterfaces[0];
        return this.getClazz(index, type);
    }


    default Class<T> getGenericSuperclass(Class<?> clazz, int index) {
        ParameterizedType type = (ParameterizedType) clazz.getGenericSuperclass();
        return this.getClazz(index, type);
    }

    private Class<T> getClazz(int index, ParameterizedType type) {
        if (type == null) {
            throw new IllegalStateException("Generic superclass is not a ParameterizedType");
        }

        Type[] actualTypeArguments = type.getActualTypeArguments();
        if (actualTypeArguments.length < index + 1) {
            throw new IllegalStateException("Expected a ParameterizedType with at least two type arguments");
        }

        Type actualTypeArgument = actualTypeArguments[index];

        if (actualTypeArgument instanceof Class<?>) {
            return (Class<T>) actualTypeArgument;
        } else {
            throw new IllegalStateException("Unexpected type argument: " + actualTypeArgument);
        }
    }
}
